import strHtml from "./UserPage.html";
import { DomUtils } from "../../utils/DomUtils";
import {
  fetchUsers,
  createUser,
  updateUser,
  deleteUser,
} from "../../services/api"; // 从 api.js 引入

export class UserPage {
  constructor() {
    this.dom = null;
    this.userList = [];
    this.table = null;
    this.userModal = null;
    this.deleteConfirmModal = null;
    this.pendingDeleteId = null;
  }

  async render() {
    const html = strHtml;
    this.dom = DomUtils.convertToDom(html);

    this._bindEvents();
    await this._loadData();
    this._initDataTable();

    return this.dom;
  }

  async _loadData() {
    try {
      const res = await fetchUsers();
      this.userList = res.data || res || [];
    } catch (err) {
      console.error("加载用户失败", err);
      this.userList = [];
    }
  }

  _bindEvents() {
    this.userModal = new bootstrap.Modal(this.dom.querySelector("#userModal"));
    this.deleteConfirmModal = new bootstrap.Modal(
      this.dom.querySelector("#deleteConfirmModal")
    );

    const form = this.dom.querySelector("#userForm");

    this.dom.querySelector("#btnAdd").addEventListener("click", () => {
      form.reset();
      form.querySelector("#userId").value = "";
      this.dom.querySelector("#userModalLabel").textContent = "新增用户";
      this.userModal.show();
    });

    this.dom
      .querySelector("#saveUserBtn")
      .addEventListener("click", async () => {
        const id = form.querySelector("#userId").value;
        const username = form.querySelector("#userName").value;
        const email = form.querySelector("#userEmail").value;
        const realName = form.querySelector("#realName").value;
        const password = form.querySelector("#userPassword").value;
        const role = form.querySelector("#userRole").value;

        if (!username || !email || !realName || !role || (!id && !password)) {
          alert("请完整填写用户信息！");
          return;
        }

        const user = { username, email, realName, role, password };

        try {
          if (id) {
            await updateUser(id, user);
          } else {
            await createUser(user);
          }
          this.userModal.hide();
          await this._loadData();
          this._refreshTable();
        } catch (err) {
          alert("保存失败！");
          console.error(err);
        }
        console.log("提交的 user 对象:", user);
      });

    this.dom
      .querySelector("#confirmDeleteBtn")
      .addEventListener("click", async () => {
        if (this.pendingDeleteId !== null) {
          try {
            await deleteUser(this.pendingDeleteId);
            this.pendingDeleteId = null;
            this.deleteConfirmModal.hide();
            await this._loadData();
            this._refreshTable();
          } catch (err) {
            alert("删除失败！");
            console.error(err);
          }
        }
      });
  }

  _initDataTable() {
    this.table = window
      .$(this.dom.querySelector("#basic-datatable"))
      .DataTable({
        data: this.userList,
        lengthChange: false,
        searching: true,
        columns: [
          { data: "username", title: "用户名" },
          { data: "role", title: "角色" },
          { data: "realName", title: "真实姓名" },
          { data: "email", title: "邮箱" },
          {
            data: "password",
            title: "密码",
            defaultContent: "******", // 显示占位符而不是真实密码
            render: function (data) {
              return data ? "******" : "";
            },
          }, // 如果有密码数据也显示为星号 },

          {
            data: null,
            orderable: false,
            render: (data, type, row) => {
              return `
              <button class="btn btn-sm btn-warning me-1 btn-edit" data-id="${row.userId}">修改</button>
              <button class="btn btn-sm btn-danger btn-delete" data-id="${row.userId}">删除</button>
            `;
            },
          },
        ],
        pageLength: 10,
        destroy: true,
      });

    this._bindRowEvents();
  }

  _refreshTable() {
    this.table.clear().rows.add(this.userList).draw();
    this._bindRowEvents();
  }

  _bindRowEvents() {
    const form = this.dom.querySelector("#userForm");

    setTimeout(() => {
      this.dom.querySelectorAll(".btn-edit").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const id = e.target.dataset.id;
          const user = this.userList.find((u) => u.userId == id);
          if (!user) return;

          form.querySelector("#userId").value = user.userId;
          form.querySelector("#userName").value = user.username;
          form.querySelector("#userRole").value = user.role;
          form.querySelector("#realName").value = user.realName;
          form.querySelector("#userEmail").value = user.email;
          form.querySelector("#userPassword").value = ""; // 密码不回显

          this.dom.querySelector("#userModalLabel").textContent = "修改用户";
          this.userModal.show();
        });
      });

      this.dom.querySelectorAll(".btn-delete").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          this.pendingDeleteId = e.target.dataset.id;
          this.deleteConfirmModal.show();
        });
      });
    }, 0);
  }
}
